package com.example.zhinongbao.adapter;


import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.zhinongbao.model.Address;
import com.example.zhinongbao.R;
import java.util.List;

public class AddressAdapter extends RecyclerView.Adapter<AddressAdapter.ViewHolder> {

    private List<Address> addressList;
    private OnAddressClickListener listener;

    public interface OnAddressClickListener {
        void onAddressClick(Address address);
        void onEditClick(Address address);
        void onDeleteClick(Address address);
        void onSetDefault(Address address);
    }

    public AddressAdapter(List<Address> addressList, OnAddressClickListener listener) {
        this.addressList = addressList;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_address, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Address address = addressList.get(position);

        holder.tvName.setText(address.getName());
        holder.tvPhone.setText(address.getPhone());
        holder.tvAddress.setText(address.getFullAddress());

        // 显示默认地址标识
        if (address.isDefault()) {
            holder.ivDefault.setVisibility(View.VISIBLE);
        } else {
            holder.ivDefault.setVisibility(View.INVISIBLE);
        }

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> listener.onAddressClick(address));
        holder.btnEdit.setOnClickListener(v -> listener.onEditClick(address));
        holder.btnDelete.setOnClickListener(v -> listener.onDeleteClick(address));
        holder.layoutDefault.setOnClickListener(v -> listener.onSetDefault(address));
    }

    @Override
    public int getItemCount() {
        return addressList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvName, tvPhone, tvAddress;
        ImageView ivDefault;
        Button btnEdit, btnDelete;
        LinearLayout layoutDefault;

        ViewHolder(View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_name);
            tvPhone = itemView.findViewById(R.id.tv_phone);
            tvAddress = itemView.findViewById(R.id.tv_address);
            ivDefault = itemView.findViewById(R.id.iv_default);
            btnEdit = itemView.findViewById(R.id.btn_edit);
            btnDelete = itemView.findViewById(R.id.btn_delete);
            layoutDefault = itemView.findViewById(R.id.layout_default);
        }
    }
}